<?php
/**
 * Created by PhpStorm.
 * UsersF: Mloong
 * Date: 2018/12/25
 * Time: 9:12
 */

namespace app\admin\controller;


use app\admin\model\Banner as BannerModel;
use app\admin\service\BannerService;
use app\lib\exception\MysqlErrorException;
use think\facade\Request;

class Banner extends BaseController
{
    /**、
     * 中间件，剔除post为空的属性
     * @var array
     */
    protected $middleware = [
        'UnsetNull' => ['only' => ['addBannerPic'] ]
    ];
    #
    public function allBanner()
    {
        return $this->fetch('/Banner/allBanner');
    }
    # 添加或者更新轮播图
    public function addBanner($id = '')
    {
        if($id !== null){
            $result = BannerModel::findOne($id);
            $this->assign('info',$result);
        }
        return $this->fetch('/Banner/addBanner');
    }
    # 添加轮播图
    public function addBannerPic()
    {
        $post = $this->request->postData;
        $service = new BannerService();
        $result = $service->addOrUpBanner($post);
        if($result['success'] == true){
            $this->success($result['msg']);
        }else{
            $this->error($result['msg']);
        }
    }
    # 轮播图分页
    public function allBannerPage($page,$limit)
    {
        $model  = new BannerModel();
        $layuiPage = new \Page\Page($model,$page,$limit,[],[]);
        $result = $layuiPage->layuiPage();
        return json($result);
    }
    # 删除轮播图
    public function delBanner()
    {
        $banner_id = Request::post('banner_id');
        $result = BannerModel::delOne($banner_id);
        if (!$result){
            throw new MysqlErrorException([
                'code' => 300,
                'msg' => '删除失败'
            ]);
        }
        return json([
            'code' => 200
        ]);
    }
}